<?php

/**
 * @author Lam Vu Nhat
 * @copyright 2011
 */
class Muare_Storage_Model_Avatar extends XFCP_Muare_Storage_Model_Avatar
{
	/**
	 * Re-crops an existing avatar with a square, starting at the specified coordinates
	 *
	 * @param integer $userId
	 * @param integer $x
	 * @param integer $y
	 *
	 * @return array Changed avatar fields
	 */
	public function recropAvatar($userId, $x, $y)
	{
		throw new XenForo_Exception('recropAvatar be disabled by Muare Team.', true);
	}

	/**
	 * Writes out an avatar.
	 *
	 * @param integer $userId
	 * @param string $size Size code
	 * @param string $tempFile Temporary avatar file. Will be moved.
	 *
	 * @return boolean
	 */
	protected function _writeAvatar($userId, $size, $tempFile)
	{
		if (!in_array($size, array_keys(self::$_sizes)))
		{
			throw new XenForo_Exception('Invalid avatar size.');
		}

		// Upload to server
		$cURL = new Muare_Storage_Curl();
		$filePath = $this->getAvatarFilePath($userId, $size);

		$cURL->delete($filePath); // Delete old file if exits
		$result = $cURL->upload($filePath, $tempFile);
		unlink($tempFile);

		$filePath = $this->getAvatarFilePath($userId, $size);
		$directory = dirname($filePath);

		if ($cURL->getCode() != 200)
		{
			if (XenForo_Application::debugMode())
			{
				throw new XenForo_Exception($result, true);
			}
			else
			{
				throw new XenForo_Exception('Upload error! Please try again.', true);
			}
		}

		return true;
	}

	/**
	 * Get the file path to an avatar.
	 *
	 * @param integer $userId
	 * @param string $size Size code
	 *
	 * @return string
	 */
	public function getAvatarFilePath($userId, $size)
	{
		return sprintf('avatars/%s/%d/%d.jpg', $size, floor($userId / 1000), $userId);
	}

	/**
	 * Deletes a user's avatar.
	 *
	 * @param integer $userId
	 * @param boolean $updateUser
	 *
	 * @return array Changed avatar fields
	 */
	public function deleteAvatar($userId, $updateUser = true)
	{
		foreach (array_keys(self::$_sizes) AS $size)
		{
			$filePath = $this->getAvatarFilePath($userId, $size);
			$cURL = new Muare_Storage_Curl();
			$cURL->delete($filePath);
		}

		$dwData = array(
			'avatar_date' => 0,
			'avatar_width' => 0,
			'avatar_height' => 0,
			'avatar_crop_x' => 0,
			'avatar_crop_y' => 0,
			'gravatar' => '',
		);

		if ($updateUser)
		{
			$dw = XenForo_DataWriter::create('XenForo_DataWriter_User', XenForo_DataWriter::ERROR_SILENT);
			$dw->setExistingData($userId);
			$dw->bulkSet($dwData);
			$dw->save();
		}

		return $dwData;
	}
}
